package com.ins1st.plus.web.admin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ins1st.plus.api.system.log.service.SysLogApi;
import com.ins1st.plus.api.system.menu.service.SysMenuApi;
import com.ins1st.plus.api.system.user.entity.SysUser;
import com.ins1st.plus.api.system.user.service.SysUserApi;
import com.ins1st.plus.base.BaseController;
import com.ins1st.plus.config.shiro.ShiroExt;
import com.ins1st.plus.core.annotation.Req4Json;
import com.ins1st.plus.core.annotation.Req4Model;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @program: ins1st-plus
 * @description: 主控制器
 * @author: coderSun
 * @create: 2019-09-03 13:27
 **/
@Controller
@RequestMapping(value = "/")
public class SysIndexController extends BaseController {

    @Reference
    SysMenuApi sysMenuApi;
    @Reference
    SysUserApi sysUserApi;
    @Reference
    SysLogApi sysLogApi;

    @Bean(name = "sysUserApi")
    public SysUserApi getSysUserApi() {
        return sysUserApi;
    }

    @Bean(name = "sysMenuApi")
    public SysMenuApi getSysMenuApi() {
        return sysMenuApi;
    }

    @Bean(name = "sysLogApi")
    public SysLogApi sysLogApi(){
        return sysLogApi;
    }
    /**
     * 登入页面
     *
     * @return
     */
    @Req4Model(value = "/login")
    public String login() {
        return "pages/login.html";
    }

    /**
     * 登入
     *
     * @param sysUser
     * @return
     */
    @Req4Json(value = "/doLogin", log = "登入")
    public Object doLogin(SysUser sysUser) throws Exception {
        UsernamePasswordToken upt = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getUserPassword());
        try {
            ShiroExt.getSubject().login(upt);
        } catch (AuthenticationException e) {
            return error(e.getMessage());
        }
        return success();
    }

    /**
     * 主页
     *
     * @return
     */
    @Req4Model(value = "/index")
    public String index(Model model) {
        model.addAttribute("menus", this.sysMenuApi.queryMenus4Index(ShiroExt.getUser().getId()));
        return "pages/index.html";
    }

    /**
     * 欢迎页
     *
     * @return
     */
    @Req4Model(value = "/welcome")
    public String welcome() {
        return "pages/welcome.html";
    }


    /**
     * 退出登入
     */
    @Req4Model(value = "/logout")
    public void logout() {
        ShiroExt.getSubject().logout();
    }
}
